﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using AForge.Imaging.Filters;
using System.IO;
using System.Threading;
using AForge.Video.FFMPEG;
using Emgu.CV.OCR;
using Emgu.CV.Structure;
using System.Runtime.InteropServices;
using System.Collections;

namespace New_Ocr
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region Strukturák
        public struct Thresholdd
        {
            public int threshold_ertek;
            public double sharpen_sigma;
            public int sharpen_size;
            public bool mean;
        }
        public struct Ido
        {
            public string ido;
            public int darab;
            public List<Thresholdd> thresholdok;
        }
        public struct NyersAdat
        {
            public string ido;
            public int th;
            public double sigma;
            public int size;
            public bool mean;
        }
        public struct EmguKepek
        {
            public Bitmap kep;
            public int th;
            public double sigma;
            public int size;
            public bool mean;
        }
        public struct KepKonverzio
        {
            public double sigma;
            public int size;
            public int threshold;
            public bool mean;
        }
        public struct ElsoOcrAdatok
        {
            public string file_name;
            public Rectangle rectangle;
            public int frame;
            public string nyersIdo;
            public string beirtIdo;
            public List<KepKonverzio> kepkonverziok;
        }
        public struct Time
        {
            public int min;
            public int sec;

            public Time decSec(int ennyivel)
            {
                int sec_s = sec;
                int min_s = min;
                for (int i = 0; i < ennyivel; i++)
                {

                    if (sec_s > 0)
                        sec_s = sec_s - 1;
                    else
                    {
                        if (min_s > 0)
                        {
                            sec_s = 59;
                            min_s = min_s - 1;
                        }
                    }
                }
                Time t = new Time();
                t.min = min_s;
                t.sec = sec_s;
                return t;
            }

            public int kivonas(Time egyik, Time masik)
            {
                int min = egyik.min - masik.min;
                int sec = egyik.sec - masik.sec + (min * 60);
                return sec;
            }
        }
        public struct SqlAdat
        {
            public int frame;
            public Time ido;
        }
        #endregion

        #region Globálisak
        System.Threading.Thread th_konverzio;
        System.Threading.Thread th_ora;
        System.Threading.Thread th_statusz;

        AForge.Video.FFMPEG.VideoFileReader reader = new AForge.Video.FFMPEG.VideoFileReader();
        string global_dir = "";
        int hol_jarunk = 0, vissza = 0, video_szam = 0, szalak = 0, mostani_dir = 0, mostani_video = 0;
        Rectangle keret = new Rectangle();
        String file_name;
        Bitmap global_kep;

        NyersAdat nyersadat = new NyersAdat();
        List<List<string>> global_fileok = new List<List<string>>();
        List<EmguKepek> emgu_kepek = new List<EmguKepek>();
        List<string> konyvtarak;
        List<Bitmap> kepek = new List<Bitmap>();
        List<NyersAdat> nyersadatok = new List<NyersAdat>();
        List<Ido> idok = new List<Ido>();
        Button[] gombok;
        Label[] labelek;
        Label[] allapot;
        Label[] hanyadik_frame;
        Label[] video_avaible;
        Label[] dat_avaible;
        Label[] complete_avaible;
        #endregion

        public void clear()
        {
            nyersadatok = new List<NyersAdat>();
            idok = new List<Ido>();
            reader = new AForge.Video.FFMPEG.VideoFileReader();
            hol_jarunk = 0;
            vissza = 0;
            video_szam = 0;
            keret = new Rectangle();
            file_name = "";
            kepek = new List<Bitmap>();

        }
        public List<Ido> thresholdTesteles()
        {
            Emgu.CV.OCR.Tesseract tesseract1 = new Emgu.CV.OCR.Tesseract("tessdata", "my", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY);
            Emgu.CV.OCR.Tesseract tesseract2 = new Emgu.CV.OCR.Tesseract("tessdata", "eng", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_DEFAULT);
            tesseract1.SetVariable("tessedit_char_whitelist", ":0123456789");
            tesseract2.SetVariable("tessedit_char_whitelist", ":0123456789");
            if (keret.Height < 1 || keret.Width < 1)
            {
                keret.Height = 2;
                keret.Width = 2;
            }
            Bitmap local_kep = global_kep.Clone(keret, global_kep.PixelFormat);
            Grayscale gray = new Grayscale(0.2125, 0.7154, 0.0721);
            if (local_kep.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
                local_kep = gray.Apply(local_kep);

            int also_ertek = kepth(local_kep, 18);
            int felso_ertek = kepth(local_kep, 8);

            ResizeBilinear local_resize = new ResizeBilinear(local_kep.Width * 3, local_kep.Height * 3);
            local_kep = local_resize.Apply(local_kep);

            Mean mean = new Mean();
            int novekmeny = ((felso_ertek - also_ertek) / 5);
            if (novekmeny < 1)
            {
                novekmeny = 1;
            }
            for (int h = 5; h <= 19; h += 7)
            {
                for (double t = 3; t > h / 6.8; t -= 1)
                {
                    GaussianSharpen local_sharpen = new GaussianSharpen(t, h);
                    Bitmap gausienezett = local_sharpen.Apply(local_kep);

                    for (int i = also_ertek; i < felso_ertek; i += novekmeny)
                    {
                        Threshold local_th = new Threshold(i);
                        Bitmap thzott = local_th.Apply(gausienezett);
                        for (int r = 0; r <= 1; r++)
                        {
                            Bitmap local_mean;
                            if (r == 0)
                                local_mean = mean.Apply(thzott);
                            else
                                local_mean = thzott;

                            Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte> local_ekep = new Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte>(local_mean);
                            tesseract1.Recognize(local_ekep);
                            string szoveg1 = tesseract1.GetText();
                            szoveg1 = szoveg1.Trim('\n', '\r', ' ', '\t');
                            nyersadat.ido = szoveg1;
                            nyersadat.mean = (r == 0) ? true : false;
                            nyersadat.sigma = t;
                            nyersadat.size = h;
                            nyersadat.th = i;
                            nyersadatok.Add(nyersadat);
                        }
                    }
                }
            }

            for (int i = also_ertek; i < felso_ertek; i += novekmeny)
            {
                Threshold local_th = new Threshold(i);
                Bitmap thzott = local_th.Apply(local_kep);
                for (int r = 0; r <= 1; r++)
                {
                    Bitmap local_mean;
                    if (r == 0)
                        local_mean = mean.Apply(thzott);
                    else
                        local_mean = thzott;

                    Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte> local_ekep = new Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte>(local_mean);
                    tesseract1.Recognize(local_ekep);
                    string szoveg1 = tesseract1.GetText();
                    szoveg1 = szoveg1.Trim('\n', '\r', ' ', '\t');
                    nyersadat.ido = szoveg1;
                    nyersadat.mean = (r == 0) ? true : false;
                    nyersadat.sigma = 0;
                    nyersadat.size = 0;
                    nyersadat.th = i;
                    nyersadatok.Add(nyersadat);
                }
            }

            foreach (NyersAdat ny in nyersadatok)
            {
                if (idok.Count(a => a.ido == ny.ido) < 1)
                {
                    Ido ido = new Ido();
                    ido.ido = ny.ido;
                    ido.darab = nyersadatok.Count(a => a.ido == ny.ido);
                    Thresholdd th = new Thresholdd();
                    ido.thresholdok = new List<Thresholdd>();
                    List<NyersAdat> temp = nyersadatok.Where(a => a.ido == ny.ido).ToList();
                    foreach (NyersAdat n in temp)
                    {
                        th.mean = n.mean;
                        th.sharpen_sigma = n.sigma;
                        th.sharpen_size = n.size;
                        th.threshold_ertek = n.th;
                        ido.thresholdok.Add(th);
                    }
                    idok.Add(ido);
                }
            }

            idok.RemoveAll(a => a.ido == "");
            idok = idok.OrderByDescending(a => a.darab).ToList();

            return idok;
        }
        public List<Ido> kivalogatas()
        {
            idok.Clear();
            System.Threading.ThreadStart start_konverzio = new System.Threading.ThreadStart(kepkonverziok);
            th_konverzio = new System.Threading.Thread(start_konverzio);
            th_konverzio.IsBackground = true;
            th_konverzio.Start();

            System.Threading.ThreadStart start_ora = new System.Threading.ThreadStart(elsoOraTeszteles);
            th_ora = new System.Threading.Thread(start_ora);
            th_ora.IsBackground = true;
            th_ora.Start();

            while (true)
            {
                if (!th_konverzio.IsAlive && !th_ora.IsAlive)
                {
                    // Kiválogatás
                    foreach (NyersAdat ny in nyersadatok)
                    {
                        if (idok.Count(a => a.ido == ny.ido) < 1)
                        {
                            Ido ido = new Ido();
                            ido.ido = ny.ido;
                            ido.darab = nyersadatok.Count(a => a.ido == ny.ido);
                            Thresholdd th = new Thresholdd();
                            ido.thresholdok = new List<Thresholdd>();
                            List<NyersAdat> temp = nyersadatok.Where(a => a.ido == ny.ido).ToList();
                            foreach (NyersAdat n in temp)
                            {
                                th.mean = n.mean;
                                th.sharpen_sigma = n.sigma;
                                th.sharpen_size = n.size;
                                th.threshold_ertek = n.th;
                                ido.thresholdok.Add(th);
                            }
                            idok.Add(ido);
                        }
                    }

                    idok.RemoveAll(a => a.ido == "");
                    idok = idok.OrderByDescending(a => a.darab).ToList();
                    break;
                }
                else
                    System.Threading.Thread.Sleep(20);
            }
            return idok;
        }
        public void kepkonverziok()
        {
            Bitmap ora_kep = global_kep.Clone(keret, global_kep.PixelFormat);
            ResizeBilinear resize = new ResizeBilinear(ora_kep.Width * 3, ora_kep.Height * 3);
            ora_kep = resize.Apply(ora_kep);
            Grayscale gray = new Grayscale(0.2125, 0.7154, 0.0721);
            if (ora_kep.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
                ora_kep = gray.Apply(ora_kep);
            EmguKepek ekep = new EmguKepek();

            Mean mean = new Mean();
            for (int h = 5; h <= 19; h += 7)
            {
                for (double t = 3; t > h / 6.8; t -= 0.5)
                {
                    GaussianSharpen local_sharpen = new GaussianSharpen(t, h);
                    Bitmap gausienezett = local_sharpen.Apply(ora_kep);
                    for (int i = 80; i < 200; i += 10)
                    {
                        Threshold local_th = new Threshold(i);
                        Bitmap thzott = local_th.Apply(gausienezett);
                        for (int r = 0; r <= 1; r++)
                        {
                            if (r == 0)
                                ekep.kep = mean.Apply(thzott);
                            else
                                ekep.kep = thzott;

                            ekep.mean = (r == 0) ? true : false;
                            ekep.sigma = t;
                            ekep.size = h;
                            ekep.th = i;
                            emgu_kepek.Add(ekep);
                        }
                    }
                }
            }

            for (int i = 80; i < 200; i += 10)
            {
                Threshold local_th = new Threshold(i);
                Bitmap thzott = local_th.Apply(ora_kep);
                for (int r = 0; r <= 1; r++)
                {
                    if (r == 0)
                        ekep.kep = mean.Apply(thzott);
                    else
                        ekep.kep = thzott;
                    ekep.mean = (r == 0) ? true : false;
                    ekep.sigma = 0;
                    ekep.size = 0;
                    ekep.th = i;
                    emgu_kepek.Add(ekep);
                }
            }
            th_konverzio.Abort();
        }
        public void elsoOraTeszteles()
        {
            Emgu.CV.OCR.Tesseract tesseract1 = new Emgu.CV.OCR.Tesseract("tessdata", "my", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY);
            Emgu.CV.OCR.Tesseract tesseract2 = new Emgu.CV.OCR.Tesseract("tessdata", "eng", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_DEFAULT);
            tesseract1.SetVariable("tessedit_char_whitelist", ":0123456789");
            tesseract2.SetVariable("tessedit_char_whitelist", ":0123456789");

            while (th_konverzio.IsAlive || emgu_kepek.Count > 0)
            {
                if (emgu_kepek.Count > 0)
                {
                    AForge.Imaging.Filters.ResizeBilinear resize = new AForge.Imaging.Filters.ResizeBilinear(emgu_kepek[0].kep.Width * 3, emgu_kepek[0].kep.Height * 3);
                    Bitmap temp = resize.Apply(emgu_kepek[0].kep);
                    Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte> ekep = new Emgu.CV.Image<Emgu.CV.Structure.Gray, Byte>(temp);
                    tesseract1.Recognize(ekep);
                    string szoveg1 = tesseract1.GetText();
                    szoveg1 = szoveg1.Trim('\n', '\r', ' ', '\t');
                    nyersadat.ido = szoveg1;
                    nyersadat.mean = emgu_kepek[0].mean;
                    nyersadat.sigma = emgu_kepek[0].sigma;
                    nyersadat.size = emgu_kepek[0].size;
                    nyersadat.th = emgu_kepek[0].th;
                    nyersadatok.Add(nyersadat);

                    tesseract2.Recognize(ekep);
                    string szoveg2 = tesseract2.GetText();
                    szoveg2 = szoveg2.Trim('\n', '\r', ' ', '\t');
                    nyersadat.ido = szoveg2;
                    nyersadatok.Add(nyersadat);

                    emgu_kepek.RemoveAt(0);
                }
                else
                    Thread.Sleep(10);
            }
            th_ora.Abort();
        }
        public List<SqlAdat> simitas(List<SqlAdat> adat, double frame_per_sec)
        {
            List<SqlAdat> vegleges = new List<SqlAdat>();
            Time t = new Time();
            double atlag = 0;

            if (frame_per_sec == 0)
            {
                List<double> atlagok = new List<double>();
                for (int i = 1; i < adat.Count; i++)
                {
                    for (int o = 1; o < adat.Count; o++)
                    {
                        if (adat[i].frame == adat[o].frame)
                            continue;

                        double p = Math.Abs((adat[i].frame - adat[o].frame) / (t.kivonas(adat[i].ido, adat[o].ido)));
                        atlagok.Add(p);
                    }
                }

                int count = 0;
                double leg_gyakoribb = 0;
                foreach (double d in atlagok.Distinct())
                {
                    int c = atlagok.Count(a => a == d);
                    if (c > count)
                    {
                        count = c;
                        leg_gyakoribb = d;
                    }
                }
                atlagok.RemoveAll(a => ((a < leg_gyakoribb - (leg_gyakoribb * 0.1)) || (a > leg_gyakoribb + (leg_gyakoribb * 0.1))));
                atlag = atlagok.Average();
            }
            else
                atlag = frame_per_sec;

            int elorol = 0, hatulrol = adat.Count - 1;
            while (elorol < hatulrol)
            {
                double most_atlag = Math.Abs(adat[elorol].frame - adat[hatulrol].frame) / kivonas(adat[elorol].ido, adat[hatulrol].ido);
                if (Math.Abs(most_atlag - atlag) < (atlag * 0.1))
                {
                    /////////////
                    List<int> szamok = new List<int>();
                    for (int a = elorol + 1; a < hatulrol; a++)
                    {
                        Time vizsgalt_ido = adat[a].ido.decSec(1);
                        if (adat.Exists(g => g.ido.Equals(vizsgalt_ido)))
                            szamok.Add((int)((adat[a].frame - adat[elorol].frame) - (atlag * a)));
                    }

                    List<int> kozelites = new List<int>();
                    for (int a = -6; a <= 6; a++)
                    {
                        int kozelito_count = 0;
                        for (int b = 0; b < szamok.Count; b++)
                        {
                            try
                            {
                                double valami = szamok.Where(j => (j < atlag * 0.1)).Average();
                                if (Math.Abs(szamok[b] + a) < valami / 2)
                                    kozelito_count++;
                            }
                            catch
                            { }
                        }
                        kozelites.Add(kozelito_count);
                    }

                    if (vegleges.Count < 1)
                    {
                        int elso_valtas_kozelites = (int)kozelites.Average();
                        SqlAdat v = new SqlAdat();
                        v.frame = adat[elorol].frame + elso_valtas_kozelites;
                        v.ido = adat[elorol].ido;
                        vegleges.Add(v);
                    }

                    int ennyit_megy = elorol + kivonas(adat[elorol].ido, adat[hatulrol].ido);
                    for (int eleje = elorol; eleje <= ennyit_megy; eleje++)
                    {
                        SqlAdat temp = new SqlAdat();
                        if (!(adat.Exists(h => h.ido.Equals(adat[elorol].ido.decSec(eleje - elorol)))))
                        {
                            temp.frame = adat[eleje - 1].frame + 1;
                            temp.ido = adat[elorol].ido.decSec(eleje - elorol);
                            adat.Insert(eleje - 1, temp);
                        }
                    }
                    adat = adat.OrderBy(a => a.frame).ToList();

                    for (int eleje = elorol; eleje <= ennyit_megy; eleje++)
                    {
                        if (vegleges.Exists(h => h.ido.Equals(adat[eleje].ido)))
                            continue;
                        SqlAdat temp = new SqlAdat();

                        double szamitas = Math.Abs((kivonas(adat[elorol].ido, adat[eleje].ido) * atlag) - (adat[eleje].frame - adat[elorol].frame));
                        if (szamitas > 5)
                        {
                            temp.frame = (int)(adat[elorol].frame + (kivonas(adat[elorol].ido, adat[eleje].ido) * atlag));
                            temp.ido = adat[eleje].ido;
                            vegleges.Add(temp);
                        }
                        else
                        {
                            temp.frame = adat[eleje].frame;
                            temp.ido = adat[eleje].ido;
                            vegleges.Add(temp);
                        }

                    }

                    elorol = hatulrol;
                    hatulrol = adat.Count - 1;
                }
                else
                {
                    hatulrol--;
                }
            }
            return vegleges;
        }
        public int kivonas(Time egyik, Time masik)
        {
            int min = egyik.min - masik.min;
            int sec = egyik.sec - masik.sec + (min * 60);
            return sec;
        }
        public void ocrezes(object param)
        {
            int index = (int)param;
            allapot[index].Invoke((MethodInvoker)(() => allapot[index].Text = "Running"));
            string konyvtar = konyvtarak[index];

            while (true)
            {
                List<string> files = Directory.EnumerateFiles(konyvtar, "*.wmv").ToList();
                string dat_eleresi_ut = ""; string wmv_eleresi_ut = "";
                for (int mindig_az_elso = 0; mindig_az_elso < files.Count; mindig_az_elso++)
                {
                    string dat_eleresi_ut_temp = Path.GetDirectoryName(files[mindig_az_elso]) + "\\" + Path.GetFileNameWithoutExtension(files[mindig_az_elso]) + ".dat";
                    string sql_eleresi_ut_temp = Path.GetDirectoryName(files[mindig_az_elso]) + "\\" + Path.GetFileNameWithoutExtension(files[mindig_az_elso]) + "_sql2.txt";
                    if (File.Exists(dat_eleresi_ut_temp) && !File.Exists(sql_eleresi_ut_temp))
                    {
                        dat_eleresi_ut = dat_eleresi_ut_temp;
                        wmv_eleresi_ut = files[mindig_az_elso];
                        break;
                    }
                }

                if (dat_eleresi_ut != "")
                {
                    ElsoOcrAdatok elso_adat = adatokBeolvasasa(dat_eleresi_ut);
                    bool ora_eltunt = false;

                    List<SqlAdat> video_sql = new List<SqlAdat>();
                    string[] set = elso_adat.beirtIdo.Split(':');
                    Time elso_ido = new Time();
                    elso_ido.min = int.Parse(set[0]);
                    elso_ido.sec = int.Parse(set[1]);

                    List<string> tess_eredmenyek = new List<string>();
                    int tesscount = 0;
                    VideoFileReader local_reader = new VideoFileReader();
                    Bitmap local_kep;

                    Emgu.CV.OCR.Tesseract tesseract1 = new Emgu.CV.OCR.Tesseract("tessdata", "my", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY);
                    Emgu.CV.OCR.Tesseract tesseract2 = new Emgu.CV.OCR.Tesseract("tessdata", "eng", Emgu.CV.OCR.Tesseract.OcrEngineMode.OEM_DEFAULT);
                    tesseract1.SetVariable("tessedit_char_whitelist", ":0123456789");
                    tesseract2.SetVariable("tessedit_char_whitelist", ":0123456789");

                    #region file nyitas es elso framehez lepes
                    try
                    {
                        local_reader.Open(wmv_eleresi_ut);
                    }
                    catch
                    {
                        MessageBox.Show("Can't open video file " + wmv_eleresi_ut);
                    }
                    for (int i = 0; i < elso_adat.frame; i++)
                        local_reader.ReadVideoFrame();
                    #endregion

                    int frame_per_sec = local_reader.FrameRate + 1;
                    IFilter gray = new Grayscale(0.2125, 0.7154, 0.0721);

                    #region threshold atlag
                    int th_gausien = 0, g_nelkul = 0, g_vel = 0, th_gnelkul = 0;
                    foreach (KepKonverzio k in elso_adat.kepkonverziok)
                    {
                        if (k.size != 0 && k.sigma != 0)
                        {
                            g_vel++;
                            th_gausien += k.threshold;
                        }
                        else
                        {
                            th_gnelkul += k.threshold;
                            g_nelkul++;
                        }
                    }
                    int th_atlag_g = th_gausien / g_vel;

                    int th_atlag_n = 0;
                    if (g_nelkul != 0)
                        th_atlag_n = th_gnelkul / g_nelkul;
                    #endregion

                    while (true)
                    {
                        hanyadik_frame[index].Invoke((MethodInvoker)(() => hanyadik_frame[index].Text = "" + Path.GetFileNameWithoutExtension(wmv_eleresi_ut) + "" + Path.GetExtension(wmv_eleresi_ut) + " => " + tesscount.ToString() + " frame"));
                        local_kep = local_reader.ReadVideoFrame();
                        if (local_kep == null)
                            break;

                        Bitmap kiskep = local_kep.Clone(elso_adat.rectangle, local_kep.PixelFormat);
                        if (kiskep.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
                            kiskep = gray.Apply(kiskep);

                        IFilter resize = new ResizeBilinear(kiskep.Width * 3, kiskep.Height * 3);
                        kiskep = resize.Apply(kiskep);

                        if (g_vel > 0)
                        {
                            #region sima konverziok
                            IFilter mean = new Mean();
                            for (int o = 5; o <= 19; o += 14)
                            {
                                for (double p = 3; p > o / 6.8; p -= 1)
                                {
                                    IFilter sharpen = new GaussianSharpen(p, o);
                                    Bitmap sharpenezett = sharpen.Apply(kiskep);
                                    for (int i = th_atlag_g - 10; i <= th_atlag_g + 10; i += 10)
                                    {
                                        IFilter threshold = new Threshold(i);
                                        Bitmap thresholdozott = threshold.Apply(sharpenezett);
                                        for (int m = 0; m <= 1; m++)
                                        {
                                            if (m == 0)
                                                thresholdozott = mean.Apply(thresholdozott);

                                            Emgu.CV.Image<Gray, Byte> ekep = new Emgu.CV.Image<Gray, Byte>(thresholdozott);
                                            tesseract1.Recognize(ekep);
                                            string nyers1 = tesseract1.GetText();
                                            nyers1 = nyers1.Replace("\n", "");
                                            nyers1 = nyers1.Replace("\r", "");
                                            nyers1 = nyers1.Replace("\t", "");
                                            nyers1 = nyers1.Replace(" ", "");
                                            tess_eredmenyek.Add(nyers1);

                                            tesseract2.Recognize(ekep);
                                            string nyers2 = tesseract2.GetText();
                                            nyers2 = nyers2.Replace("\n", "");
                                            nyers2 = nyers2.Replace("\r", "");
                                            nyers2 = nyers2.Replace("\t", "");
                                            nyers2 = nyers2.Replace(" ", "");
                                            tess_eredmenyek.Add(nyers2);
                                        }
                                    }
                                }
                            }
                            #endregion
                        }

                        if (g_nelkul > 0)
                        {
                            #region gausien nelkuli
                            IFilter mean = new Mean();
                            for (int i = th_atlag_n - 10; i <= th_atlag_n + 10; i += 10)
                            {
                                IFilter threshold = new Threshold(i);
                                Bitmap thresholdozott = threshold.Apply(kiskep);
                                for (int m = 0; m <= 1; m++)
                                {
                                    if (m == 0)
                                        thresholdozott = mean.Apply(thresholdozott);

                                    Emgu.CV.Image<Gray, Byte> ekep = new Emgu.CV.Image<Gray, Byte>(thresholdozott);
                                    tesseract1.Recognize(ekep);
                                    string nyers1 = tesseract1.GetText();
                                    nyers1 = nyers1.Replace("\n", "");
                                    nyers1 = nyers1.Replace("\r", "");
                                    nyers1 = nyers1.Replace("\t", "");
                                    nyers1 = nyers1.Replace(" ", "");
                                    tess_eredmenyek.Add(nyers1);

                                    tesseract2.Recognize(ekep);
                                    string nyers2 = tesseract2.GetText();
                                    nyers2 = nyers2.Replace("\n", "");
                                    nyers2 = nyers2.Replace("\r", "");
                                    nyers2 = nyers2.Replace("\t", "");
                                    nyers2 = nyers2.Replace(" ", "");
                                    tess_eredmenyek.Add(nyers2);
                                }
                            }
                            #endregion
                        }

                        int teljes_lista_count = tess_eredmenyek.Count;
                        tess_eredmenyek.RemoveAll(a => a == "");
                        tess_eredmenyek.RemoveAll(a => a.Count() < 1);
                        tess_eredmenyek.RemoveAll(a => a[a.Count() - 1] == ':' || a[0] == ':');

                        #region idok kiszamolasa
                        string ido_most = elso_ido.sec.ToString();
                        string ido_lessz = elso_ido.decSec(1).sec.ToString();
                        if (elso_ido.sec < 10)
                            ido_most = "0" + elso_ido.sec.ToString();
                        if (elso_ido.decSec(1).sec < 10)
                            ido_lessz = "0" + elso_ido.decSec(1).sec.ToString();
                        #endregion

                        #region counter1 ls counter2 megszámolása
                        int counter1 = 0, counter2 = 0;
                        foreach (string st in tess_eredmenyek)
                        {
                            string mp_2 = "";
                            char mp_1;
                            mp_2 = st[st.Count() - 2] + "" + st[st.Count() - 1];
                            mp_1 = st[st.Count() - 1];
                            if (mp_1 == ido_most[0] || mp_2 == ido_most )
                                counter1++;

                            if (mp_1 == ido_lessz[0] || mp_2 == ido_lessz)
                                counter2++;
                        }
                        #endregion

                        if (counter2 > counter1 * 1.2)
                        {
                            elso_ido = elso_ido.decSec(1);
                            SqlAdat adat = new SqlAdat();
                            adat.frame = tesscount + elso_adat.frame;
                            adat.ido = elso_ido;
                            video_sql.Add(adat);
                        }
                        else
                        {
                            List<int> eredmenyek_count = new List<int>();
                            List<Time> idok = new List<Time>();
                            foreach (string s in tess_eredmenyek)
                            {
                                Time t = new Time(); // még csak kettőspontot néz
                                if (s.Contains(':'))
                                {
                                    string[] temp = s.Split(':');
                                    if (temp.Count() > 1)
                                    {
                                        if (temp[0].Count() > 1)
                                            t.min = int.Parse(temp[0][0] + "" + temp[0][1]);
                                        else
                                            if(temp[0].Count() > 0)
                                                t.min = int.Parse(temp[0][0] + "");

                                        int utolso = temp.Count() - 1;
                                        if (temp[utolso].Count() > 1)
                                            t.sec = int.Parse(temp[utolso][temp[utolso].Count() - 2] + "" + temp[utolso][temp[utolso].Count() - 1]);
                                        else
                                            t.sec = int.Parse("" + temp[utolso][temp[utolso].Count() - 1]);

                                        idok.Add(t);
                                    }
                                }
                                else
                                {
                                    if (s.Count() >= 2 )
                                    {
                                        SqlAdat e = video_sql[video_sql.Count-1];
                                        if (e.ido.min > 10)
                                        {
                                            if (s.Count() > 3)
                                            {
                                                t.min = int.Parse(s[0] + "" + s[1]);
                                                t.sec = int.Parse(s[s.Count() - 2] + "" + s[s.Count() - 1]);
                                                idok.Add(t);
                                            }
                                            if (s.Count() > 2)
                                            {
                                                t.min = int.Parse(s[0] + "" + s[1]);
                                                t.sec = int.Parse("" + s[s.Count() - 1]);
                                                idok.Add(t);
                                            }
                                        }

                                        if (e.ido.min < 10 && e.ido.min > 1 )
                                        {
                                            // 10 min alatt és 1 min felett és valtania kellett volna
                                        }

                                        if (e.ido.min < 1)
                                        {
                                            // 10 min felett és valtania kellett volna vagy szerintünk 
                                        }
                                    }
                                }
                            }

                            List<Time> idok_dist = new List<Time>(idok.Distinct());
                            foreach (Time t in idok_dist)
                            {
                                int c = idok.Count(a => a.sec == t.sec);
                                eredmenyek_count.Add(c);
                            }

                            int max = 0;
                            if (eredmenyek_count.Count > 0)
                                max = eredmenyek_count.Max();

                            if ((counter1 < (teljes_lista_count / 5) && counter2 < (teljes_lista_count / 5)) || ora_eltunt)
                            {
                                ora_eltunt = true;
                                for (int i = 0; i < idok_dist.Count; i++)
                                {
                                    if (eredmenyek_count[i] > (teljes_lista_count * 0.2) && eredmenyek_count[i] == max)
                                    {
                                        Time t = new Time();
                                        if (video_sql.Count != 0)
                                        {
                                            int icount = video_sql.Count - 1;
                                            double eltelt_frame = tesscount - video_sql[icount].frame;
                                            double sec_kulombseg = (double)t.kivonas(video_sql[icount].ido, idok_dist[i]);
                                            double egyik = (double)eltelt_frame / 30;
                                            double masik = (double)eltelt_frame / 70;
 
                                            if (idok_dist[i].sec < elso_ido.sec && egyik > (double)sec_kulombseg && sec_kulombseg > masik)
                                            {
                                                elso_ido.sec = idok_dist[i].sec;
                                                SqlAdat adat = new SqlAdat();
                                                adat.frame = tesscount + elso_adat.frame;
                                                adat.ido = elso_ido;
                                                video_sql.Add(adat);
                                                ora_eltunt = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        tess_eredmenyek.Clear();
                        tesscount++;
                    }

                    StreamWriter writer1 = new StreamWriter(Path.GetDirectoryName(wmv_eleresi_ut) + "\\" + Path.GetFileNameWithoutExtension(wmv_eleresi_ut) + "_s.txt");
                    foreach (SqlAdat s in video_sql)
                        writer1.WriteLine(s.frame + " ; " + s.ido.min + ":" + s.ido.sec);
                    writer1.Close();

                    List<SqlAdat> vegleges = simitas(video_sql, frame_per_sec);

                    #region fileba iras
                    StreamWriter writer = new StreamWriter(Path.GetDirectoryName(wmv_eleresi_ut) + "\\" + Path.GetFileNameWithoutExtension(wmv_eleresi_ut) + "_sql2.txt");
                    foreach (SqlAdat s in vegleges)
                        writer.WriteLine(s.frame + " ; " + s.ido.min + ":" + s.ido.sec);
                    writer.Close();
                    #endregion

                    local_reader.Close();
                }
                else
                {
                    gombok[index].Invoke((MethodInvoker)(() => gombok[index].Show()));
                    allapot[index].Invoke((MethodInvoker)(() => allapot[index].Text = "Finish"));
                    szalak--;
                    break;
                }
            }
        }
        public ElsoOcrAdatok adatokBeolvasasa(string filename)
        {
            ElsoOcrAdatok adatok = new ElsoOcrAdatok();
            StreamReader string_reader = new StreamReader(Path.GetDirectoryName(filename) + "\\" + Path.GetFileNameWithoutExtension(filename) + ".dat");
            string elso_sor = string_reader.ReadLine();
            string[] temp = elso_sor.Split(';');
            adatok.file_name = Path.GetDirectoryName(filename) + "\\" + Path.GetFileNameWithoutExtension(filename) + ".wmv";
            adatok.rectangle = new Rectangle(int.Parse(temp[0]), int.Parse(temp[1]), int.Parse(temp[2]), int.Parse(temp[3]));
            adatok.frame = int.Parse(temp[4]);
            adatok.nyersIdo = temp[5];
            adatok.beirtIdo = temp[6];
            adatok.kepkonverziok = new List<KepKonverzio>();
            while (!string_reader.EndOfStream)
            {
                KepKonverzio konverzio = new KepKonverzio();
                string bealitas = string_reader.ReadLine();
                string[] bealitasok = bealitas.Split(';');
                konverzio.sigma = double.Parse(bealitasok[0]);
                konverzio.size = int.Parse(bealitasok[1]);
                konverzio.threshold = int.Parse(bealitasok[2]);
                konverzio.mean = bool.Parse(bealitasok[3]);
                adatok.kepkonverziok.Add(konverzio);
            }
            return adatok;
        }
        public void elemekFeltoltese(int konyvtar_index, string konyvtar)
        {
            gombok[konyvtar_index] = new Button();
            gombok[konyvtar_index].Show();
            gombok[konyvtar_index].Location = new System.Drawing.Point(25, 30 + (konyvtar_index * 30));
            gombok[konyvtar_index].Name = "Start";
            gombok[konyvtar_index].Size = new System.Drawing.Size(75, 23);
            gombok[konyvtar_index].TabIndex = 0;
            gombok[konyvtar_index].Text = "Start\n" + konyvtar_index;
            panel1.Controls.Add(gombok[konyvtar_index]);
            gombok[konyvtar_index].UseVisualStyleBackColor = true;
            gombok[konyvtar_index].Click += new EventHandler(button_Click);

            labelek[konyvtar_index] = new Label();
            panel1.Controls.Add(labelek[konyvtar_index]);
            labelek[konyvtar_index].Show();
            labelek[konyvtar_index].AutoSize = true;
            labelek[konyvtar_index].Location = new System.Drawing.Point(110, 32 + (konyvtar_index * 30));
            labelek[konyvtar_index].Name = "label";
            labelek[konyvtar_index].Text = konyvtar;

            allapot[konyvtar_index] = new Label();
            panel1.Controls.Add(allapot[konyvtar_index]);
            allapot[konyvtar_index].Show();
            allapot[konyvtar_index].AutoSize = true;
            allapot[konyvtar_index].Location = new System.Drawing.Point(400, 32 + (konyvtar_index * 30));
            allapot[konyvtar_index].Name = "Ready";
            allapot[konyvtar_index].Text = "Ready";

            hanyadik_frame[konyvtar_index] = new Label();
            panel1.Controls.Add(hanyadik_frame[konyvtar_index]);
            hanyadik_frame[konyvtar_index].Show();
            hanyadik_frame[konyvtar_index].AutoSize = true;
            hanyadik_frame[konyvtar_index].Location = new System.Drawing.Point(500, 32 + (konyvtar_index * 30));
            hanyadik_frame[konyvtar_index].Name = "Frame";
            hanyadik_frame[konyvtar_index].Text = "0";

            video_avaible[konyvtar_index] = new Label();
            panel1.Controls.Add(video_avaible[konyvtar_index]);
            video_avaible[konyvtar_index].Show();
            video_avaible[konyvtar_index].AutoSize = true;
            video_avaible[konyvtar_index].Location = new System.Drawing.Point(700, 32 + (konyvtar_index * 30));
            video_avaible[konyvtar_index].Name = "wmv";
            video_avaible[konyvtar_index].Text = "0";

            dat_avaible[konyvtar_index] = new Label();
            panel1.Controls.Add(dat_avaible[konyvtar_index]);
            dat_avaible[konyvtar_index].Show();
            dat_avaible[konyvtar_index].AutoSize = true;
            dat_avaible[konyvtar_index].Location = new System.Drawing.Point(720, 32 + (konyvtar_index * 30));
            dat_avaible[konyvtar_index].Name = "dat";
            dat_avaible[konyvtar_index].Text = "0";

            complete_avaible[konyvtar_index] = new Label();
            panel1.Controls.Add(complete_avaible[konyvtar_index]);
            complete_avaible[konyvtar_index].Show();
            complete_avaible[konyvtar_index].AutoSize = true;
            complete_avaible[konyvtar_index].Location = new System.Drawing.Point(740, 32 + (konyvtar_index * 30));
            complete_avaible[konyvtar_index].Name = "sql";
            complete_avaible[konyvtar_index].Text = "0";

        }
        public void statusUpdate()
        {
            while (true)
            {
                try
                {
                    List<Button> buttomok = gombok.Where(a => a != null).ToList();
                    for (int i = 0; i < buttomok.Count; i++)
                    {
                        List<string> wmv_files = Directory.EnumerateFiles(konyvtarak[i], "*.wmv").ToList();
                        List<string> dat_files = Directory.EnumerateFiles(konyvtarak[i], "*.dat").ToList();
                        List<string> sql_files = Directory.EnumerateFiles(konyvtarak[i], "*.txt").ToList();

                        video_avaible[i].Invoke((MethodInvoker)(() => video_avaible[i].Text = wmv_files.Count + ""));
                        dat_avaible[i].Invoke((MethodInvoker)(() => dat_avaible[i].Text = dat_files.Count + ""));
                        complete_avaible[i].Invoke((MethodInvoker)(() => complete_avaible[i].Text = sql_files.Count + ""));
                    }

                    Thread.Sleep(10000);
                }
                catch
                {
                    Thread.Sleep(10000);
                }
            }
        }

        [DllImport("Gdi32", EntryPoint = "GetBitmapBits")]
        private extern static long GetBitmapBits([In] IntPtr hbmp, [In] int cbBuffer, [Out] byte[] lpvBits);
        [DllImport("Gdi32", EntryPoint = "GdiFlush")]
        private extern static void GdiFlush();
        public int kepth(Bitmap img, int percent)
        {
            try
            {

                if (img.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
                {
                    Grayscale grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                    img = grayscaleFilter.Apply(img);
                }
                Byte[] kep1 = new Byte[(img.Size.Width * img.Size.Height) * 4];
                IntPtr hbmp = img.GetHbitmap();
                GdiFlush();
                GetBitmapBits(hbmp, kep1.Length * Marshal.SizeOf(typeof(byte)), kep1);
                Byte[] kep2 = new Byte[img.Size.Width * img.Size.Height];

                List<List<Byte>> list2d = new List<List<byte>>();
                for (int x = 0; x < (img.Size.Height - 1); x++) { for (int y = 0; y < (img.Size.Width - 1); y++) { kep2[(x * img.Size.Width) + y] = kep1[(x * 4 * img.Size.Width) + y * 4]; } }

                for (int x = 0; x < (img.Size.Height - 1); x++) { List<Byte> temp = new List<byte>(); for (int y = 0; y < (img.Size.Width - 1); y++) { temp.Add(kep2[(x) * (img.Size.Width) + (y)]); } list2d.Add(temp); }
                List<int> th = new List<int>();
                for (int i = 0; i < 256; i++)
                {
                    int count = 0;
                    foreach (List<Byte> t in list2d)
                    {
                        count += t.Count(a => (a == Convert.ToByte(i)));
                    }
                    th.Add(count);
                }
                int pixelek = 0;
                int megnezettek = 0;
                while (pixelek < (double)(kep2.Count() * ((double)percent / 100)))
                {
                    pixelek = pixelek + th[(th.Count - 1) - megnezettek];
                    megnezettek++;
                }
                return (255 - megnezettek);
            }
            catch
            {
                return 0;
            }
        }
        public void faFrissitese()
        {
            treeView1.Nodes.Clear();
            for (int i = 0; i < global_fileok.Count; i++)
            {
                TreeNode node = new TreeNode();
                node = treeView1.Nodes.Add(Path.GetFileNameWithoutExtension(konyvtarak[i]));
                for (int o = 0; o < global_fileok[i].Count; o++)
                {
                    string datfile = Path.GetDirectoryName(global_fileok[i][o]) + "\\" + Path.GetFileNameWithoutExtension(global_fileok[i][o]) + ".dat";
                    string local_string = "";
                    if (File.Exists(datfile))
                    {
                        StreamReader local_reader = new StreamReader(datfile);
                        string[] local_adat = local_reader.ReadLine().Split(';');
                        local_reader.Close();
                        local_string = local_adat[local_adat.Count() - 1];
                    }
                    node.Nodes.Add(Path.GetFileNameWithoutExtension(global_fileok[i][o]) + "    " + local_string);
                }
            }
            treeView1.ExpandAll();
        }
        public void kiskepRefresh()
        {
            Bitmap local_kep = new Bitmap(global_kep);
            Bitmap kis_local_kep = new Bitmap(global_kep);
            try
            {
                kis_local_kep = local_kep.Clone(keret, local_kep.PixelFormat);
                ResizeBilinear local_resize = new ResizeBilinear(kis_local_kep.Width * 2, kis_local_kep.Height * 2);
                kis_local_kep = local_resize.Apply(kis_local_kep);
                pictureBox2.Show();
            }
            catch
            {
                pictureBox2.Hide();
            }
            pictureBox2.Image = kis_local_kep;
            pictureBox1.Show();
            pictureBox1.Image = local_kep;
            button2.Hide();
        }
        public void boxRefresh()
        {
            pictureBox1.Refresh();
            pictureBox2.Refresh();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Hide();
            label3.Hide();
            label4.Hide();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            idok.Clear();
            nyersadatok.Clear();
            video_szam = treeView1.SelectedNode.Index;
            if (reader.IsOpen && global_fileok.Count > 0 && video_szam < global_fileok[mostani_dir].Count && (keret.X != 0 && keret.Y != 0))
            {
                label3.Show();

                idok = thresholdTesteles();
                if (idok.Count < 1)
                {
                    textBox1.Text = "null";
                }
                else
                    textBox1.Text = idok[0].ido;

                button2.Show();
                video_szam++;
                label3.Hide();
            }

            if (reader.IsOpen && (file_name != "" && file_name != null) && (keret.X != 0 && keret.Y != 0))
            {
                label3.Show();
                idok = thresholdTesteles();
                if (idok.Count < 1)
                {
                    textBox1.Text = "null";
                }
                else
                    textBox1.Text = idok[0].ido;

                button2.Show();
                label3.Hide();
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string uj_ido = textBox1.Text;
            textBox1.Text = "Wait";
            textBox1.Refresh();

            if (uj_ido.Contains(':'))
            {
                if (video_szam > 0)
                {
                    List<Ido> valogatott1 = idok.Where(a => a.ido == uj_ido).ToList();
                    string nelkul = uj_ido.Replace(":", "");
                    List<Ido> valogatott2 = idok.Where(a => a.ido == nelkul).ToList();
                    if (valogatott1.Count > 0 || valogatott2.Count > 0)
                    {
                        if (valogatott1.Count > 0)
                        {
                            StreamWriter writer = new StreamWriter(Path.GetDirectoryName(global_fileok[mostani_dir][mostani_video]) + "\\" + Path.GetFileNameWithoutExtension(global_fileok[mostani_dir][mostani_video]) + ".dat");
                            writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott1[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                            foreach (Thresholdd i in valogatott1[0].thresholdok)
                            {
                                writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                            }
                            writer.Close();
                        }
                        else
                        {
                            StreamWriter writer = new StreamWriter(Path.GetDirectoryName(global_fileok[mostani_dir][mostani_video]) + "\\" + Path.GetFileNameWithoutExtension(global_fileok[mostani_dir][mostani_video]) + ".dat");
                            writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott2[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                            foreach (Thresholdd i in valogatott2[0].thresholdok)
                            {
                                writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                            }
                            writer.Close();
                        }
                    }
                    else
                    {
                        idok = kivalogatas();
                        uj_ido = textBox1.Text;
                        valogatott1 = idok.Where(a => a.ido == uj_ido).ToList();
                        nelkul = uj_ido.Replace(":", "");
                        valogatott2 = idok.Where(a => a.ido == nelkul).ToList();

                        if (valogatott1.Count > 0 || valogatott2.Count > 0)
                        {
                            if (valogatott1.Count > 0)
                            {
                                StreamWriter writer = new StreamWriter(Path.GetDirectoryName(global_fileok[mostani_dir][mostani_video]) + "\\" + Path.GetFileNameWithoutExtension(global_fileok[mostani_dir][mostani_video]) + ".dat");
                                writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott1[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                                foreach (Thresholdd i in valogatott1[0].thresholdok)
                                {
                                    writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                                }
                                writer.Close();
                            }
                            else
                            {
                                StreamWriter writer = new StreamWriter(Path.GetDirectoryName(global_fileok[mostani_dir][mostani_video]) + "\\" + Path.GetFileNameWithoutExtension(global_fileok[mostani_dir][mostani_video]) + ".dat");
                                writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott2[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                                foreach (Thresholdd i in valogatott2[0].thresholdok)
                                {
                                    writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                                }
                                writer.Close();
                            }
                        }
                        else
                            MessageBox.Show("Can't OCR!");
                    }
                    if (video_szam < global_fileok[mostani_dir].Count && global_fileok.Count > mostani_dir)
                    {
                        kepek.Clear();
                        mostani_video++;
                        faFrissitese();
                        nyersadatok.Clear();
                        idok.Clear();
                        textBox1.Text = "";
                        hol_jarunk = 0;
                        label4.Text = "frame: " + hol_jarunk;

                        if (reader.IsOpen)
                            reader.Close();
                        reader.Open(global_fileok[mostani_dir][mostani_video]);
                        global_kep = reader.ReadVideoFrame();
                        Bitmap local_kep = new Bitmap(global_kep);
                        Graphics g = Graphics.FromImage(local_kep);
                        Bitmap kis_global_kep = local_kep.Clone(keret, global_kep.PixelFormat);
                        g.DrawRectangle(new Pen(new SolidBrush(Color.Red)), keret);
                        ResizeBilinear local_resize = new ResizeBilinear(kis_global_kep.Width * 2, kis_global_kep.Height * 2);
                        kis_global_kep = local_resize.Apply(kis_global_kep);
                        pictureBox2.Show();
                        pictureBox2.Image = kis_global_kep;
                        pictureBox1.Show();
                        pictureBox1.Image = local_kep;
                        button2.Hide();
                        boxRefresh();
                        treeView1.SelectedNode = treeView1.Nodes[mostani_dir].Nodes[mostani_video];
                    }
                    else
                    {
                        kepek.Clear();
                        mostani_video++;
                        if (global_fileok[mostani_dir].Count >= mostani_video && global_fileok.Count > mostani_dir + 1)
                        {
                            mostani_dir++;
                            mostani_video = 0;
                            video_szam = 0;
                            faFrissitese();
                            nyersadatok.Clear();
                            idok.Clear();
                            textBox1.Text = "";
                            hol_jarunk = 0;
                            label4.Text = "frame: " + hol_jarunk;

                            if (reader.IsOpen)
                                reader.Close();
                            reader.Open(global_fileok[mostani_dir][mostani_video]);
                            global_kep = reader.ReadVideoFrame();
                            Bitmap local_kep = new Bitmap(global_kep);
                            Graphics g = Graphics.FromImage(local_kep);
                            Bitmap kis_global_kep = local_kep.Clone(keret, global_kep.PixelFormat);
                            g.DrawRectangle(new Pen(new SolidBrush(Color.Red)), keret);
                            ResizeBilinear local_resize = new ResizeBilinear(kis_global_kep.Width * 2, kis_global_kep.Height * 2);
                            kis_global_kep = local_resize.Apply(kis_global_kep);
                            pictureBox2.Show();
                            pictureBox2.Image = kis_global_kep;
                            pictureBox1.Show();
                            pictureBox1.Image = local_kep;
                            button2.Hide();
                            boxRefresh();
                            treeView1.SelectedNode = treeView1.Nodes[mostani_dir].Nodes[mostani_video];
                        }
                        else
                        {
                            MessageBox.Show("No more video available!");
                            kepek.Clear();
                            mostani_dir = 0;
                            mostani_video = 0;
                            faFrissitese();
                            nyersadatok.Clear();
                            idok.Clear();
                            textBox1.Text = "";
                            hol_jarunk = 0;
                            label4.Text = "frame: " + hol_jarunk;

                            if (reader.IsOpen)
                                reader.Close();
                            reader.Open(global_fileok[mostani_dir][mostani_video]);
                            global_kep = reader.ReadVideoFrame();
                            Bitmap local_kep = new Bitmap(global_kep);
                            Graphics g = Graphics.FromImage(local_kep);
                            Bitmap kis_global_kep = local_kep.Clone(keret, global_kep.PixelFormat);
                            g.DrawRectangle(new Pen(new SolidBrush(Color.Red)), keret);
                            ResizeBilinear local_resize = new ResizeBilinear(kis_global_kep.Width * 2, kis_global_kep.Height * 2);
                            kis_global_kep = local_resize.Apply(kis_global_kep);
                            pictureBox2.Show();
                            pictureBox2.Image = kis_global_kep;
                            pictureBox1.Show();
                            pictureBox1.Image = local_kep;
                            button2.Hide();
                            boxRefresh();
                            treeView1.SelectedNode = treeView1.Nodes[mostani_dir].Nodes[mostani_video];
                        }
                    }
                }

                if (file_name != "" && file_name != null)
                {
                    uj_ido = textBox1.Text;
                    textBox1.Text = "";
                    string[] ido_t = idok[0].ido.Split(':');
                    List<Ido> valogatott1 = idok.Where(a => a.ido == uj_ido).ToList();
                    string nelkul = uj_ido.Replace(":", "");
                    List<Ido> valogatott2 = idok.Where(a => a.ido == nelkul).ToList();
                    if (valogatott1.Count > 0 || valogatott2.Count > 0)
                    {
                        if (valogatott1.Count > 0)
                        {
                            StreamWriter writer = new StreamWriter(Path.GetDirectoryName(file_name) + "\\" + Path.GetFileNameWithoutExtension(file_name) + ".dat");
                            writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott1[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                            foreach (Thresholdd i in valogatott1[0].thresholdok)
                            {
                                writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                            }
                            writer.Close();
                        }
                        else
                        {
                            StreamWriter writer = new StreamWriter(Path.GetDirectoryName(file_name) + "\\" + Path.GetFileNameWithoutExtension(file_name) + ".dat");
                            writer.WriteLine(keret.X + ";" + keret.Y + ";" + keret.Width + ";" + keret.Height + ";" + hol_jarunk + ";" + valogatott2[0].ido + ";" + uj_ido); //keret, frame, mi idönk, beírt ido
                            foreach (Thresholdd i in valogatott2[0].thresholdok)
                            {
                                writer.WriteLine(i.sharpen_sigma + ";" + i.sharpen_size + ";" + i.threshold_ertek + ";" + i.mean);
                            }
                            writer.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Can't OCR!");
                    }
                }
            }
            else
                MessageBox.Show("Missing colon ! ");

            if (reader.IsOpen && global_fileok.Count > 0 && video_szam < global_fileok[mostani_dir].Count && (keret.X != 0 && keret.Y != 0))
            {
                label3.Show();

                idok = thresholdTesteles();
                if (idok.Count < 1)
                {
                    textBox1.Text = "null";
                }
                else
                    textBox1.Text = idok[0].ido;

                button2.Show();
                video_szam++;
                label3.Hide();
            }

            if (reader.IsOpen && (file_name != "" && file_name != null) && (keret.X != 0 && keret.Y != 0))
            {
                label3.Show();
                idok = thresholdTesteles();
                if (idok.Count < 1)
                {
                    textBox1.Text = "null";
                }
                else
                    textBox1.Text = idok[0].ido;

                button2.Show();
                label3.Hide();
            }
        }
        private void vissza100_Click(object sender, EventArgs e)
        {
            if (reader.IsOpen)
            {
                if (hol_jarunk > 100)
                {
                    if (kepek.Count < 100)
                    {
                        global_kep = kepek[kepek.Count - 1];
                        pictureBox1.Image = global_kep;
                        boxRefresh();
                        hol_jarunk -= kepek.Count;
                        vissza += kepek.Count;
                    }
                    else
                    {
                        global_kep = kepek[hol_jarunk - 101];
                        pictureBox1.Image = global_kep;
                        boxRefresh();
                        hol_jarunk -= 100;
                        vissza += 100;
                    }
                    label4.Text = "Frame: " + hol_jarunk.ToString();
                    label4.Show();
                }
            }
        }
        private void elore100_Click(object sender, EventArgs e)
        {
            if (reader.IsOpen)
            {
                if (vissza == 0)
                {
                    for (int i = 0; i < 100; i++)
                    {
                        global_kep = reader.ReadVideoFrame();
                        kepek.Add(global_kep);
                        pictureBox1.Image = global_kep;
                        boxRefresh();
                    }
                    hol_jarunk += 100;
                }
                if (vissza > 0 && vissza < 100)
                {
                    global_kep = kepek[hol_jarunk + vissza - 1];
                    pictureBox1.Image = global_kep;
                    boxRefresh();
                    hol_jarunk += vissza;
                    vissza = 0;
                }
                if (vissza > 100)
                {
                    global_kep = kepek[hol_jarunk + 100];
                    pictureBox1.Image = global_kep;
                    boxRefresh();
                    hol_jarunk += 100;
                    vissza -= 100;
                }
                label4.Text = "Frame: " + hol_jarunk.ToString();
                label4.Show();
            }
        }
        private void vissza1_Click(object sender, EventArgs e)
        {
            if (reader.IsOpen)
            {
                if (hol_jarunk > 1)
                {
                    if (kepek.Count < 100)
                    {
                        if (vissza == 0)
                        {
                            global_kep = kepek[hol_jarunk - 2];
                            pictureBox1.Image = global_kep;
                        }
                        else
                        {
                            global_kep = kepek[hol_jarunk - 1];
                            pictureBox1.Image = global_kep;
                        }
                        boxRefresh();
                        hol_jarunk -= 1;
                        vissza += 1;
                    }
                    else
                    {
                        global_kep = kepek[hol_jarunk - 1];
                        pictureBox1.Image = global_kep;
                        boxRefresh();
                        hol_jarunk -= 1;
                        vissza += 1;
                    }
                }
                label4.Text = "Frame: " + hol_jarunk.ToString();
                label4.Show();
            }
        }
        private void elore1_Click(object sender, EventArgs e)
        {
            if (reader.IsOpen)
            {
                if (vissza == 1)
                    vissza = 0;

                if (vissza == 0)
                {
                    global_kep = reader.ReadVideoFrame();
                    kepek.Add(global_kep);
                    pictureBox1.Image = global_kep;
                    boxRefresh();
                    hol_jarunk += 1;
                }
                if (vissza > 0)
                {
                    global_kep = kepek[hol_jarunk + 1];
                    pictureBox1.Image = kepek[hol_jarunk + 1];
                    boxRefresh();
                    hol_jarunk += 1;
                    vissza -= 1;
                }
                label4.Text = "Frame: " + hol_jarunk;
                label4.Show();
            }
        }
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            using (Pen pen = new Pen(Color.Red, 1))
            {
                e.Graphics.DrawRectangle(pen, keret);
            }
        }
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                keret = new Rectangle(keret.Left, keret.Top, e.X - keret.Left, e.Y - keret.Top);

                boxRefresh();
                this.Invalidate();
            }
        }
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Bitmap local_kep = new Bitmap(global_kep);
                pictureBox1.Image = local_kep;
                keret = new Rectangle(e.X, e.Y, 0, 0);
                this.Invalidate();
                boxRefresh();
            }

        }
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                try
                {
                    Bitmap k = global_kep;
                    Bitmap kk = k.Clone(keret, k.PixelFormat);
                    AForge.Imaging.Filters.ResizeBilinear resize_k = new AForge.Imaging.Filters.ResizeBilinear(kk.Width * 2, kk.Height * 2);
                    pictureBox2.Show();
                    kk = resize_k.Apply(kk);
                    pictureBox2.Image = kk;
                }
                catch
                { }
            }
        }
        private void o_file_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                clear();
                reader.Open(openFileDialog1.FileName);
                global_kep = reader.ReadVideoFrame();
                hol_jarunk++;
                kepek.Add(global_kep);
                pictureBox1.Show();
                pictureBox1.Image = global_kep;
                file_name = openFileDialog1.FileName;
                label4.Text = "Frame: " + hol_jarunk.ToString();
                label4.Show();
            }
        }
        public void button_Click(object sender, EventArgs e)
        {
            if (szalak < Environment.ProcessorCount)
            {
                Button button = sender as Button;
                button.Hide();

                string[] temp = button.Text.Split('\n');
                int index = int.Parse(temp[1]);

                ParameterizedThreadStart start = new ParameterizedThreadStart(ocrezes);
                Thread newThread = new Thread(start);
                newThread.IsBackground = true;
                newThread.Start(index);
                szalak++;
            }
            else
                MessageBox.Show("Too much thread!");
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        private void open_dir_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                clear();
                global_dir = folderBrowserDialog1.SelectedPath;
                konyvtarak = Directory.EnumerateDirectories(global_dir).ToList();
                foreach (string s in konyvtarak)
                {
                    List<string> fileok_temp = Directory.EnumerateFiles(s, "*.wmv").ToList();
                    global_fileok.Add(fileok_temp);
                }
                try
                {
                    faFrissitese();
                    treeView1.SelectedNode = treeView1.Nodes[mostani_dir].Nodes[mostani_video];
                }
                catch
                { }
                if (reader.IsOpen)
                    reader.Close();
                try
                {
                    reader.Open(global_fileok[0][0]);
                    global_kep = reader.ReadVideoFrame();
                    pictureBox1.Show();
                    pictureBox1.Image = global_kep;
                    label4.Text = "frame: " + hol_jarunk.ToString();
                    label4.Show();
                    boxRefresh();
                }
                catch
                { }
                // //////////////////////
                gombok = new Button[1000];
                labelek = new Label[1000];
                allapot = new Label[1000];
                video_avaible = new Label[1000];
                dat_avaible = new Label[1000];
                complete_avaible = new Label[1000];
                hanyadik_frame = new Label[1000];
                konyvtarak = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToList();
                string sortores = "Selected directory:  " + folderBrowserDialog1.SelectedPath;

                selectDir.Text = sortores;
                foreach (string konyvtar in konyvtarak)
                {
                    int konyvtar_index = konyvtarak.IndexOf(konyvtar);

                    if (Directory.EnumerateFiles(konyvtar, "*.wmv").Count() > 0)
                    {
                        elemekFeltoltese(konyvtar_index, konyvtar);
                    }
                    else
                        MessageBox.Show("No video");
                }

                if (th_statusz != null)
                    th_statusz.Abort();

                System.Threading.ThreadStart start_statusz = new System.Threading.ThreadStart(statusUpdate);
                th_statusz = new System.Threading.Thread(start_statusz);
                th_statusz.IsBackground = true;
                th_statusz.Start();
            }
        }
        private void treeView1_NodeMouseDoubleClick_1(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                mostani_dir = treeView1.SelectedNode.Parent.Index;
                mostani_video = treeView1.SelectedNode.Index;
                reader.Open(global_fileok[mostani_dir][mostani_video]);
                global_kep = reader.ReadVideoFrame();
                pictureBox1.Show();
                pictureBox1.Image = global_kep;
                label4.Text = "Frame: " + hol_jarunk.ToString();
                label4.Show();
                kiskepRefresh();
                boxRefresh();
                video_szam = mostani_video;
            }
            catch (Exception ez)
            {
                MessageBox.Show(ez.ToString());
            }
        }
    }
}
